#include <iostream>
#include <string>
#include <cstring>
#include <thread>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

int sockfd = -1;
std::string serverip;
uint16_t serverport;

void InitClient(const std::string &serverip, uint16_t &serverport)
{
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket error" << std::endl;
    }
}

void recver() // 接受消息
{
    while (true)
    {
        // 从服务端读
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        char buffer[1024];
        int m = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&tmp, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cerr << buffer << std::endl;//往2号文件描述符中输入
        }
    }
}

void sender() // 发送消息
{
    // 获取服务端socket
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while (true)
    {
        std::cout << "Please Enter@ ";
        std::string line;
        std::getline(std::cin, line);

        // 写给服务端
        sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));
    }
}

void Usage(std::string proc) // 使用手册
{
    std::cout << "Usage: " << proc << " clientip clientport" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    serverip = argv[1];
    serverport = std::stoi(argv[2]);
    InitClient(serverip, serverport);

    //使用多线程进行消息的接收和发送
    std::thread trecv(recver); //接收消息
    std::thread tsend(sender); // 发送消息

    trecv.join();
    tsend.join();

    return 0;
}